# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy
from pagemagic.utils.adminutils import create_preview_field, create_link_field
#from django.core.files.storage import FileSystemStorage
import os

#class MyFilestorage(FileSystemStorage):
#    pass
#my_filestorage = MyFilestorage()

def make_generate_filename(upload_to_dir, attname):
    def generate_filename(instance, filename):
        path = os.path.join(upload_to_dir, filename)
        print getattr(instance, attname).name, '==', path
        if instance.pk and getattr(instance, attname).name == path:
            print 'delete'
            getattr(instance, attname).delete()
        return path
    return generate_filename


class Text(models.Model):
    _cache = {}
    name = models.CharField(ugettext_lazy('name'), max_length=255,
        help_text=ugettext_lazy('Name for access from code'),
        unique=True, db_index=True,
    )
    text = models.TextField(ugettext_lazy('text'))

    def save(self, *args, **kwargs):
        super(Text, self).save(*args, **kwargs)
        self.__class__._cache = {}

    @classmethod
    def get(cls, name):  # TODO make separate cache table
        try:
            return cls.objects.get(name=name).text
        except:
            return ''
#        for i in range(2): #@UnusedVariable
#            item = cls._cache.get(name)
#            if item:
#                return item
#            # update cache
#            cls._cache = dict((t.name, t.text) for t in cls.objects.all())
#        return ''

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ('name',)
        verbose_name = ugettext_lazy('small text')
        verbose_name_plural = ugettext_lazy('small texts')


class Image(models.Model):
    image = models.ImageField(ugettext_lazy('Image'),
        upload_to=make_generate_filename(getattr(settings, 'SPARE_IMAGES_UPLOAD_TO', 'spares/images'), 'image'))
    description = models.CharField(ugettext_lazy('Description'), max_length=512, blank=True)
    preview_image = create_preview_field(ugettext_lazy('Preview'), 'image', 'description')
    adm_preview_image = create_preview_field(ugettext_lazy('Preview'), 'image', 'description',
        max_size=(800, 1000))

    def adm_path(self):
        return self.image.url
    adm_path.short_description = ugettext_lazy('image path')

    def adm_code(self):
        return unicode(self.preview_image())
    adm_code.short_description = ugettext_lazy('HTML')

    def save(self, *args, **kwargs):
        self.description = self.description.strip()
        if not self.description:
            self.description = os.path.basename(self.image.name).rsplit('.', 1)[0]

        super(Image, self).save(*args, **kwargs)

    class Meta:
        verbose_name = ugettext_lazy('image')
        verbose_name_plural = ugettext_lazy('images')

    def __unicode__(self):
        return self.description


class File(models.Model):
    file = models.FileField(ugettext_lazy('File'),
        upload_to=make_generate_filename(getattr(settings, 'SPARE_FILES_UPLOAD_TO', 'spares/files'), 'file'))
    description = models.CharField(ugettext_lazy('Description'), max_length=512)
    link = create_link_field(ugettext_lazy('Link'), 'file', 'description')

    def adm_code(self):
        return u'<a href="%s">%s</a>' % (self.link(), self.description)
    adm_code.short_description = ugettext_lazy('code')

    def __unicode__(self):
        return self.description

    class Meta:
        verbose_name = ugettext_lazy('file')
        verbose_name_plural = ugettext_lazy('files')

